package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Visitors;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VisitorsApiImpl implements VisitorsApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存访客数据
     *
     * @param visitors
     */
    @Override
    public void save(Visitors visitors) {
        //查询查询条件
        Query query = Query.query(Criteria.where("userId").is(visitors.getUserId())
                .and("visitorUserId").is(visitors.getVisitorUserId())
                .and("visitDate").is(visitors.getVisitDate()));
        //通过构造条件进行查询，判断是否有无游客，无访客保存数据
        if (!mongoTemplate.exists(query, Visitors.class)) {
            mongoTemplate.save(visitors);
        }
    }

    /**
     * 查询访客记录
     * @param date
     * @param userId
     * @return
     */
    @Override
    public List<Visitors> queryVisitors(Long date, Long userId) {
        Criteria criteria = Criteria.where("userId").is(userId);
        //判断时间是否为空
        if (date!=null){
            //查询大于当前时间的访客条件
            criteria.is("dete").gt(date);
        }
        //创建查找大于当前时间的方法
        Query query = Query.query(criteria).limit(5).with(Sort.by(Sort.Order.desc("date")));
        //开始查询
        return mongoTemplate.find(query,Visitors.class);
    }
}
